package com.example.demo;

import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.ui.Messages;

import static com.example.demo.RequestUtils.FanYi;

public class FanYiAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        // 获取密钥和密钥ID
        String secretId = getValidatedValue("SecretId", "请输入SecretId：", "SecretId不能为空！");
        if (secretId == null) return;

        String secretKey = getValidatedValue("SecretKey", "请输入SecretKey：", "SecretKey不能为空！");
        if (secretKey == null) return;

        // 获取当前打开的编辑器实例
        Editor editor = CommonDataKeys.EDITOR.getData(e.getDataContext());

        if (editor != null) {
            // 获取选择模型
            SelectionModel selectionModel = editor.getSelectionModel();

            // 检查是否有文本被选中
            if (selectionModel.hasSelection()) {
                int startOffset = selectionModel.getSelectionStart();
                int endOffset = selectionModel.getSelectionEnd();
                String selectedText = selectionModel.getSelectedText();

                Document document = editor.getDocument();

                WriteCommandAction.runWriteCommandAction(editor.getProject(), () -> {
                    try {
                        // 调用翻译功能
                        String translatedText = FanYi(selectedText, secretId, secretKey);
                        translatedText = NamingUtils.snakeToCamel(translatedText);

                        // 替换选中文本
                        document.replaceString(startOffset, endOffset, translatedText);
                    } catch (Exception ex) {
                        Messages.showErrorDialog("翻译失败：" + ex.getMessage(), "错误");
                        resetValue("SecretId");
                        resetValue("SecretKey");
                        Messages.showInfoMessage("密钥或 ID 可能错误，请重新设置。", "提示");
                    }
                });
            } else {
                Messages.showInfoMessage("请先选中文本后再操作。", "提示");
            }
        } else {
            Messages.showErrorDialog("无法获取编辑器实例，请确保焦点在编辑器窗口。", "错误");
        }
    }

    /**
     * 获取并验证值，如果用户输入错误或为空，提供重新输入的机会。
     *
     * @param key          键名
     * @param prompt       输入提示
     * @param errorMessage 错误提示
     * @return 有效的值
     */
    private String getValidatedValue(String key, String prompt, String errorMessage) {
        PropertiesComponent properties = PropertiesComponent.getInstance();
        String value = properties.getValue(key);

        while (value == null || value.isEmpty()) {
            value = Messages.showInputDialog(prompt, key, Messages.getQuestionIcon());
            if (value != null && !value.isEmpty()) {
                properties.setValue(key, value);
            } else {
                Messages.showErrorDialog(errorMessage, "错误");
                return null;
            }
        }

        return value;
    }

    /**
     * 重置指定键的值。
     *
     * @param key 键名
     */
    private void resetValue(String key) {
        PropertiesComponent.getInstance().unsetValue(key);
    }
}
